package com.block.source.service.receive;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.service.ISourceReceiveService;
import com.block.source.util.JiXiangYouQianAESUtils;
import com.block.test.reqbean.convert.CheckUserConvert;
import com.block.test.reqbean.source.CheckUserInfo;
import com.block.test.reqbean.source.JiXiangYouQianUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ld
 * @Date: 2024-08-26 11:12
 * @Description: 极享有钱
 * @Version: 1.0
 **/
@Service
public class JiXiangYouQianReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${jyh.logo.url:https://jyhdd.oss-cn-shanghai.aliyuncs.com/prodlogo/prodlogo_1724688086761337853082eae4c2f8fc365dcaf3a7e91.pic.jpg}")
    private String jyhLogoUrl;

    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getAppSecret();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        // 请求数据解密
        String paramContentData = JiXiangYouQianAESUtils.decode(apiSecret, jsonObjectParamContent);
        if (ObjectUtil.isEmpty(paramContentData)){
            sourceApiResult.setErrMsg("解密失败");
            return sourceApiResult;
        }
        JiXiangYouQianUserInfo jiXiangYouQianUserInfo = JSON.parseObject(paramContentData, JiXiangYouQianUserInfo.class);
        CheckUserInfo checkUserInfo = CheckUserConvert.jiXiangUserInfo2CheckUser(jiXiangYouQianUserInfo);
        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByParentNameAndName(checkUserInfo.getProvince(), checkUserInfo.getCity());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setErrMsg("城市信息为空");
            return sourceApiResult;
        }
        // 设置省市信息
        checkUserInfo.setCityCode(addressInfo.getCodeValue());
        checkUserInfo.setCity(addressInfo.getName());
        checkUserInfo.setProvinceCode(addressInfo.getParentCode());
        checkUserInfo.setProvince(addressInfo.getParentName());

        sourceApiResult.setCheckUserInfo(checkUserInfo);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);
        String apiSecret = sourceBaseInfo.getAppSecret();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        // 请求数据解密
        String paramContentData = JiXiangYouQianAESUtils.decode(apiSecret, jsonObjectParamContent);
        if (ObjectUtil.isEmpty(paramContentData)){
            sourceApiResult.setErrMsg("解密失败");
            return sourceApiResult;
        }
        JiXiangYouQianUserInfo jiXiangYouQianUserInfo = JSON.parseObject(paramContentData, JiXiangYouQianUserInfo.class);
        CheckUserInfo checkUserInfo = CheckUserConvert.jiXiangUserInfo2CheckUser(jiXiangYouQianUserInfo);
        checkUserInfo.setMobile(jiXiangYouQianUserInfo.getUserPhone());
        checkUserInfo.setMobileMd5(null);
        String orderNo = jsonObjectParamContent.getString("orderNo");
        if (StrUtil.isBlank(orderNo)) {
            String redisKey = StrUtil.format(RedisKeyConstant.SOURCE_CHECK_ORDER_CHANNEL, sourceBaseInfo.getChannelCode(), SecureUtil.md5(checkUserInfo.getMobile()).toLowerCase());
            orderNo = stringRedisTemplate.opsForValue().get(redisKey);
        }
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectById(orderNo);
        if (pushResultInfo == null) {
            sourceApiResult.setErrMsg("未找到订单");
            return sourceApiResult;
        }
        checkUserInfo.setOrderNo(String.valueOf(pushResultInfo.getId()));
        sourceApiResult.setCheckUserInfo(checkUserInfo);
        sourceApiResult.setSuccess(true);
        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {

        SourceApiResult sourceApiResult = new SourceApiResult();

        SpecialCostomInfo specialCostomInfo = sourceApiParam.getSpecialCostomInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        // 推送原价(分润渠道返回，固价渠道不返回)
        BigDecimal priceAmount = BigDecimal.ZERO;
        if (ObjectUtil.equals(ProfitSharingEnum.PROFITPRICE.getValue(), sourceBaseInfo.getPriceType())){
            priceAmount = pushResultInfo.getPriceAmount();//分润前价格
        }
        dataObject.put("resultCode", "000000");
        dataObject.put("resultMsg", "处理成功");
        dataObject.put("price", priceAmount);
        dataObject.put("orderNo", pushResultInfo.getId() + "");
        dataObject.put("platformName", "金耀花");
        dataObject.put("platformLogo", jyhLogoUrl);
        if (StrUtil.equals(specialCostomInfo.getInfoType(), InfoTypeEnum.APIS.getValue()) ){
            // 下游是apis 类型
            dataObject.put("exhibitionName", thirdBaseInfo.getCompanyName());
            dataObject.put("exhibitionLogo", StringUtils.isEmpty(thirdBaseInfo.getCompanyLogo())
                    ? "" : thirdBaseInfo.getCompanyLogo());
            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name",protocolInfo.getProtocolName());
                jsonObject.put("url", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else{
            // 下游是 非 apis 类型
            dataObject.put("exhibitionName", specialCostomInfo.getCompanyName());
            dataObject.put("exhibitionLogo", StringUtils.isEmpty(specialCostomInfo.getCompanyLogo())
                    ? "" : specialCostomInfo.getCompanyLogo());
            //协议地址
            JSONObject jsonObject = new JSONObject();
            ChannelInfo baseInfoByCode = channelCommonService.getChannelInfoCache(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByType(baseInfoByCode.getAppType());
            String protocolUrl = StrUtil.format("{}/page/user/newprotocol/{}.html", appInfoByAppCode.getApiUrl(),
                    pushResultInfo.getOrderNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }
        dataObject.put("protocol", jsonArray);
        sourceApiResult.setReturnObject(dataObject);
        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(Boolean.FALSE);
        JSONObject returnObject = new JSONObject();
        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();
        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject.put("resultCode", "000000");
                returnObject.put("resultMsg", sourceApiParam.getThirdBaseInfo().getCompanyName());
                sourceApiResult.setSuccess(Boolean.TRUE);
            }
        }
        sourceApiResult.setReturnObject(returnObject);
        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "500");
        returnObject.put("message", message);
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "000");
        returnObject.put("message", "推送成功");
        returnObject.put("data", new JSONObject());
        return returnObject;
    }


    @Override
    public JSONObject resultInit(String channelCode, String reqId, String action) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("systemCode", channelCode);
        returnObject.put("action", action);
        returnObject.put("requestId", reqId);
        return returnObject;
    }

    @Override
    public JSONObject getError(JSONObject resultObj, String errCode, String errMsg) {
        if (resultObj == null) {
            resultObj = new JSONObject();
        }
        resultObj.put("responseCode", errCode);
        resultObj.put("responseMsg", errMsg);
        resultObj.put("completeTime", LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        return resultObj;
    }

    @Override
    public JSONObject getError(JSONObject resultObj, String errMsg) {
        return getError(resultObj, "300008", errMsg);
    }

    @Override
    public JSONObject getSuccess(JSONObject resultObj, JSONObject dataObj) {
        resultObj.put("responseCode", "000000");
        resultObj.put("responseMsg", "处理成功");
        resultObj.put("completeTime", LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        resultObj.put("result", dataObj);
        return resultObj;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam, String mobileMd5) {
        String redisKey = StrUtil.format(RedisKeyConstant.SOURCE_CHECK_ORDER_CHANNEL, sourceBaseInfo.getChannelCode(), mobileMd5);
        stringRedisTemplate.opsForValue().set(redisKey, sourceApiParam.getSourcePushResultInfo().getId().toString(), 30, TimeUnit.MINUTES);
        return getCheckUserReturnData(sourceBaseInfo, resultInfoVO, sourceApiParam);
    }
}